//导入数据操作模块
const db = require('../db/index')

//文章分类列表
exports.getArtCates = (req, res) => {
  const sqlStr = `select * from ev_article_cate where is_delete=0 order by id asc`
  db.query(sqlStr, (err, results) => {
    if (err) return res.cc(err)
    res.send({
      status: 0,
      message: '获取文章分类成功',
      data: results
    })
  })
}
//增加文章分类
exports.addArtCates = (req, res) => {
  //判断有没有重名
  const sqlStr = `select * from ev_article_cate where name=? or alias=?`
  db.query(sqlStr, [req.body.name, req.body.alias], (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 2) return res.cc('分类名称与分类别名被占用，请更换后重试！')
    if (results.length === 1 && results[0].name === req.body.name && results[0].alias === req.body.alias) return res.cc('分类名称与分类别名被占用，请更换后重试！')
    if (results.length === 1 && results[0].name === req.body.name) return res.cc('分类名称被占用，请更换后重试！')
    if (results.length === 1 && results[0].alias === req.body.alias) return res.cc('分类别名被占用，请更换后重试！')
    //添加文章
    const sql = `insert into ev_article_cate set ?`
    db.query(sql, req.body, (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows !== 1) return res.cc('新增文章分类失败！')
      res.cc('新增文章分类成功！', 0)
    })
  })
}
//删除文章分类
exports.deleteCateById = (req, res) => {
  const sqlStr = `update ev_article_cate set is_delete=1 where id=?`
  db.query(sqlStr, req.params.id, (err, results) => {
    if (err) return res.cc(err)
    if (results.affectedRows !== 1) return res.cc('删除文章分类失败!')
    res.cc('删除文章分类成功!', 0)
  })
}
//根据ID获取文章分类的功能
exports.getArtCateById = (req, res) => {
  const sqlStr = `select * from ev_article_cate where is_delete=0 and id=?`
  db.query(sqlStr, req.params.id, (err, results) => {
    if (err) return res.cc(err)
    if (results.length !== 1) return res.cc('获取文章分类失败!')
    res.send({
      status: 0,
      message: '获取文章分类成功!',
      data: results[0]
    })
  })
}
//根据ID更新文章分类的功能
exports.updateCateById = (req, res) => {
  //判断分类名称,别名是否被占用
  const sqlStr = `select * from ev_article_cate where Id !=? and name=?`
  db.query(sqlStr, [req.body.Id, req.body.name], (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 2) return res.cc('分类名称与别名被占用，请更换后重试！')
    if (results.length === 1 && req.body.name === results[0].name && req.body.alias === results[0].alias) return res.cc('分类名称与别名被占用，请更换后重试！')
    if (results.length === 1 && req.body.name === results[0].name) return res.cc('分类名称被占用，请更换后重试!')
    if (results.length === 1 && results[0].alias === req.body.alias) return res.cc('分类别名被占用，请稍后重试！')
    //更新文章分类
    const sql = `update ev_article_cate set ? where Id=?`
    db.query(sql, [req.body, req.body.Id], (err, results) => {
      if (err) return res.cc(err)
      if (results.affectedRows !== 1) return res.cc('更新文章类别失败！')
      res.cc('更新文章类别成功!', 0)
    })
  })
}
